﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace DynamicGeometry
{
    public class PropertyGrid
    {
        public static void FillControls<T>(Panel container, T editableObject)
        {
            container.Children.Clear();
            if (editableObject == null)
            {
                return;
            }
            container.Children.Add(GetTitleControl(editableObject));
            var controls = CreateObjectControls(editableObject);
            foreach (var control in controls)
            {
                container.Children.Add(control);
            }
        }

        static UIElement GetTitleControl(object editableObject)
        {
            return new TextBlock()
            {
                Text = GetTitleString(editableObject),
                FontSize = 20,
                Margin = new Thickness(0, 0, 0, 8),
                Foreground = new SolidColorBrush(Colors.Green)
            };
        }

        static string GetTitleString(object editableObject)
        {
            var type = editableObject.GetType();
            var attribute = type.GetAttribute<PropertyGridNameAttribute>();
            if (attribute != null)
            {
                return attribute.Name;
            }
            return type.Name;
        }

        public static IEnumerable<UIElement> CreateObjectControls<T>(T editableObject)
        {
            var propertyEditorControls = GetEditableProperties(editableObject)
                .Select(p => CreatePropertyEditorControl(p, editableObject))
                .Where(c => c != null);
            var methodInvokerControls = GetCallableMethods(editableObject)
                .Select(m => CreateMethodCallerControl(m, editableObject));

            return propertyEditorControls.Concat(methodInvokerControls);
        }

        static UIElement CreateMethodCallerControl(MethodInfo m, object obj)
        {
            return new MethodCallerButton() { Method = m, Target = obj };
        }

        static IEnumerable<MethodInfo> GetCallableMethods(object editableObject)
        {
            var allMethods = editableObject.GetType().GetMethods();
            return allMethods
                .Where(m => m.ReturnType == typeof(void)
                    && !m.IsSpecialName
                    && m.IsPublic
                    && m.GetParameters().Length == 0
                    && m.HasAttribute<PropertyGridVisibleAttribute>());
        }

        static IEnumerable<IPropertyEditorFactory> mFactories;
        static IEnumerable<IPropertyEditorFactory> Factories
        {
            get
            {
                if (mFactories == null)
                {
                    mFactories = typeof(PropertyGrid).Assembly.GetTypes()
                        .Where(t => t.HasInterface<IPropertyEditorFactory>()
                            && t.IsClass && !t.IsAbstract)
                        .Select(t => Activator.CreateInstance(t) as IPropertyEditorFactory);
                }
                return mFactories;
            }
        }

        static UIElement CreatePropertyEditorControl(PropertyInfo p, object obj)
        {
            var factory = Factories.Where(f => f.SupportsProperty(p)).FirstOrDefault();
            if (factory != null)
            {
                UIElement result = factory.CreateEditor(p, obj) as UIElement;
                if (result != null)
                {
                    HookupEvents(p, result, obj);
                    return result;
                }
            }
            return null;
        }

        static void HookupEvents(PropertyInfo p, UIElement result, object obj)
        {
            var eventAttributes = p
                .GetCustomAttributes(typeof(PropertyGridEventAttribute), true)
                .OfType<PropertyGridEventAttribute>();
            if (eventAttributes != null)
            {
                foreach (var eventAttribute in eventAttributes)
                {
                    HookupEvent(result, eventAttribute, obj);
                }
            }
        }

        static void HookupEvent(UIElement control, PropertyGridEventAttribute eventAttribute, object model)
        {
            var foundEvent = ReflectionHelper.FindEventByName(control.GetType(), eventAttribute.EventName);
            if (foundEvent != null)
            {
                try
                {
                    Delegate d = Delegate.CreateDelegate(foundEvent.EventHandlerType, model, eventAttribute.HandlerName);
                    foundEvent.AddEventHandler(control, d);
                }
                catch (Exception)
                {
                }
            }
        }

        static IEnumerable<PropertyInfo> GetEditableProperties<T>(T editableObject)
        {
            return editableObject.GetType()
                .GetProperties()
                .OrderBy(p => p.Name)
                .Where(p => p.HasAttribute<PropertyGridVisibleAttribute>())
                ;
        }
    }
}
